<?php

class Acl_Acceso extends Zend_Acl {

    public function __construct() {
//ROLES
        $group_resouces = new Admin_Model_DbTable_Access();
        $auth = Zend_Auth::getInstance();

        if (!$auth->hasIdentity()) {
            $user = 'guest';
            $this->addRole(new Zend_Acl_Role($user));
            $this->add(new Zend_Acl_Resource('admin'));
            $this->allow($user, 'admin', 'admin/login');
            
            $this->allow($user, 'admin', 'admin/logout');
        } else {
            $idgroup = $auth->getIdentity()->idgroup;
            $group = new Groups_Model_DbTable_Groups();
            $user = $group->getName($idgroup);
            if ($user == 'superadmin') {
                $module = new Admin_Model_DbTable_Resources();
                $row = $module->getModules();
                $this->addRole(new Zend_Acl_Role($user));
                //  $this->add(new Zend_Acl_Resource('tarea'));

                foreach ($row as $modules) {
                    $this->add(new Zend_Acl_Resource($modules['module']));
                    $this->allow($user, $modules['module'], null);
                }
                $this->allow($user, 'tarea', null);
            } else {
                require APPLICATION_PATH . '/../library/conexion.php';
                $sql = "select G.name, R.module, R.controller, R.view 
                    from resources R, groups G, group_resources GR 
                    where G.idgroup = GR.idgroup
                    and R.idresource = GR.idresource 
                    and G.name = '$user' order by R.module";
                $stmt = new Zend_Db_Statement_Mysqli($db, $sql);
                $stmt->execute();
                $row = $stmt->fetchAll();
                $this->addRole(new Zend_Acl_Role($user));
                $module = '';
                foreach ($row as $value) {
                    if ($module != $value['module']) {
                        $module = $value['module'];
                        $this->add(new Zend_Acl_Resource($module));
                    }
                    $this->allow($user, $value['module'], $value['controller'] . '/' . $value['view']);
                    //  echo $value['module'], '/' . $value['controller'] . '/' . $value['view'] . '<br>';
                }
                if (!$this->has('admin'))
                    $this->add(new Zend_Acl_Resource('admin'));
                $this->add(new Zend_Acl_Resource('default'));
                $this->allow($user, 'admin', 'admin/login');
                $this->allow($user, 'admin', 'admin/logout');
                $this->allow($user, 'admin', 'index/index');
                $this->allow($user, 'admin', 'error/error');
                $this->allow($user, 'default', null);
            }
        }
        // $this->allow($user, 'admin', 'admin/denegado');
        //echo $user;
    }

}

?>
